//
//  ChatViewController.m
//  weibo
//
//  Created by wudongyang on 16/6/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ChatViewController.h"
#import "OtherTableViewCell.h"
#import "DSMineTableViewCell.h"
#import "ChatConsoleView.h"
#import "MyChatTableViewCell.h"
#import "BQCollectionViewCell.h"


@interface ChatViewController ()<UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain)UITableView *ChatTableView;
@property(nonatomic, retain)ChatConsoleView *chatConsoleView;
// 聊天的会话对象
@property(nonatomic, retain)EMConversation *conversation;
@end

@implementation ChatViewController

- (void)dealloc
{
    [_ChatTableView release];
    [_chatConsoleView release];
    [_conversation release];
    [super dealloc];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = DSRGBA(235, 235, 235, 1);
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    self.title = self.chatter;
    [self initUI];
    [self reloadChatRecords];
    [self registerForKeyBoardNotifications];
    // Do any additional setup after loading the view.
}
// 布局
-(void)initUI{
    self.ChatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 40) style:UITableViewStylePlain];
    self.ChatTableView.delegate = self;
    self.ChatTableView.dataSource = self;
    self.ChatTableView.backgroundColor = DSRGBA(235, 235, 235, 1);
    [self.view addSubview:self.ChatTableView];
    self.ChatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_ChatTableView release];
    
    [self.ChatTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(WIDTH, HEIGHT - 40));
//        make.bottom.mas_equalTo(self.view).offset(-40);
        
    }];
    
    [self.ChatTableView registerClass:[OtherTableViewCell class] forCellReuseIdentifier:@"otherCell"];
    
    [self.ChatTableView registerClass:[MyChatTableViewCell class] forCellReuseIdentifier:@"myCell"];
    
    // ---拖---动---时---隐---藏---键---盘
//    self.ChatTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//    [self.ChatTableView setAllowsSelection:NO];
    
    // 聊天页面的输入框
    self.chatConsoleView = [[ChatConsoleView alloc] initWithFrame:CGRectMake(0, HEIGHT - 40, WIDTH, 40)];
    self.chatConsoleView.chatter = self.chatter;
    ChatViewController *ChatVC = self;
    // block回调 点击发送按钮触发 得到输入框中的字符串
    self.chatConsoleView.buttonClicked = ^(NSString *draftText){
        
        // 发送给环信服务器
        [ChatVC sendMessageWithDraftText:draftText];
//        [ChatVC reloadChatRecords];
    
    };
    
    // 表情按钮block 回调
    self.chatConsoleView.BQButtonBlock = ^(UIButton *button){
        
//        if (button.selected == 0) {
            NSLog(@"111");
            [UIView animateWithDuration:0.25 animations:^{
                [self.ChatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
                    
                    make.top.mas_equalTo(-271);
                    
                }];
                self.chatConsoleView.frame = CGRectMake(0, HEIGHT - 40 - 271, WIDTH, 40);
                
            }];
            [self.view endEditing:YES];
        self.chatConsoleView.isBool = NO;
            // 延迟运行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.expressionView.hidden = NO;
            });

    };
    
    [self.view addSubview:self.chatConsoleView];
    
    // 创建表情View
    
    self.expressionView = [[UIView alloc] init];
    self.expressionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.expressionView];
    [_expressionView release];
    [self.expressionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.ChatTableView.mas_bottom).offset(40);
        make.left.and.right.equalTo(self.view).offset(0);
        make.size.mas_equalTo(CGSizeMake(WIDTH, 271));
        
    }];
    self.expressionView.hidden = YES;
    
    [self getData];
    // 创建表情CollectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH/8, WIDTH/8);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 271) collectionViewLayout:flowLayout];
    collectionView.backgroundColor = DSRGBA(235, 235, 235, 1);
    [self.expressionView addSubview:collectionView];
    [flowLayout release];
    [collectionView registerClass:[BQCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
}
-(void)getData{
    self.BQArray = [NSMutableArray array];
    for (int i = 0; i < 105; i++) {
        NSString *BQName = [NSString stringWithFormat:@"Expression_%d",i+1];
        [self.BQArray addObject:BQName];
    }
    NSLog(@"%@",self.BQArray);
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSLog(@"%ld",self.BQArray.count);
    return self.BQArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BQCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    item.BQName = self.BQArray[indexPath.row];
    return item;
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableString *str1 = [NSMutableString stringWithFormat:@"[%@]",self.BQArray[indexPath.row]];
    NSMutableString *str2 = [NSMutableString stringWithString:self.chatConsoleView.draftTextField.text];
    [str2 appendString:str1];
    self.chatConsoleView.draftTextField.text = str2;
    
}

- (void)didReceiveMessage:(EMMessage *)message {
    NSLog(@"收到了一条消息");
    [self reloadChatRecords];
}
// 发送消息
-(void)sendMessageWithDraftText:(NSString *)draftText{

    // 要发送的消息
    EMChatText *chatText = [[EMChatText alloc] initWithText:draftText];
   EMTextMessageBody *body = [[EMTextMessageBody alloc]initWithChatObject:chatText];
    
    EMMessage * message = [[EMMessage alloc] initWithReceiver:self.chatter bodies:@[body]];
    
    
    // 设置为单聊消息
    message.messageType = eMessageTypeChat;
    
    // 发送消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error) {
        
        // 准备发送
    } onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error) {
        [self reloadChatRecords];
        [chatText release];
        [message release];
        // 发送完成后就立马获取会话刷新列表
    } onQueue:dispatch_get_main_queue()];
    

}

// 刷新数据
-(void)reloadChatRecords{
    
    //新建/获取一个会话
    //onversationForChatter:获取或创建与self.chatter的会话
    //conversationType:会话类型
    self.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.chatter conversationType:eConversationTypeChat];
    
    [self.ChatTableView reloadData];
    
    if ([self.conversation loadAllMessages].count > 0) {
        [self.ChatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.conversation loadAllMessages].count - 1 inSection:0] atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
        
    }


}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.conversation.loadAllMessages.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"1===========");
    EMMessage *message = self.conversation.loadAllMessages[indexPath.row];
    if ([message.to isEqualToString:self.chatter]) {
        MyChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
        cell.message = message;
        
        return cell;
    } else {
    OtherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"otherCell"];
    cell.message = message;
        
    return cell;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    EMMessage *message = [self.conversation.loadAllMessages objectAtIndex:indexPath.row];
    // 聊天的文本消息体对象
    EMTextMessageBody *body = [message.messageBodies lastObject];
// 聊天消息类型
    if (body.messageBodyType == eMessageBodyType_Text) {
        CGFloat height = [OtherTableViewCell heightForCell:body.text];
        return height + 50 + 10;
    }

    return 100;

//    NSLog(@"%@",body.text);
//    CGFloat height = [OtherTableViewCell heightForCell:body.text];
//    return height + 50 + 10;


}

//注册通知中心
-(void)registerForKeyBoardNotifications{

//    // 使用NSNotificationCenter 注册观察当键盘要出现时
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didKeyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    
    // 使用NSNotificationCenter 注册观察当键盘要隐藏时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didKeyBoardWillHide:) name:UIKeyboardWillChangeFrameNotification object:nil];
    

}


// 键盘将要弹出
-(void)didKeyboardWillShow:(NSNotification *)notification {
//    NSLog(@"键盘弹起");
    // 计算键盘高度
//    NSDictionary *info = [notification userInfo];
//    NSLog(@"%@",info);
//    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//    NSLog(@"00000=%f", keyboardSize.height);

    // 输入框位置动画加载
//    [self begainMoveUpAnimation:keyboardSize.height];
    


}
// 键盘将要出现或消失
-(void)didKeyBoardWillHide:(NSNotification *)noti{
    NSLog(@"键盘消失");

    [self.ChatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.equalTo(self.view).offset(-250);
        
    }];
    self.chatConsoleView.frame = CGRectMake(0, HEIGHT - 250-40, WIDTH, 40);
//    if (rect.origin.y > 0) {
//        self.chatConsoleView.isBool = !self.chatConsoleView.isBool;
        

    }
//    self.chatConsoleView.isBool = !self.chatConsoleView.isBool;

//}
// 开始执行键盘改变后对应视图的变化
-(void)begainMoveUpAnimation:(CGFloat)height {
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    self.view.transform = CGAffineTransformTranslate(transform, 0, -height);

}
// 拖动触发
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"---");
    // 结束编辑
    if ([scrollView isKindOfClass:[UITableView class]]) {
        if (self.ChatTableView.frame.origin.y != 0) {
            NSLog(@"12234234");
            
            [UIView animateWithDuration:0.25 animations:^{
                [self.view endEditing:YES];
                [self.ChatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(0);
                    
                }];
                self.expressionView.hidden = YES;
                
                self.chatConsoleView.frame = CGRectMake(0, HEIGHT - 40, WIDTH, 40);
            }];
//            self.chatConsoleView.expressionButton.enabled = YES;
            self.chatConsoleView.isBool = NO;
        }
    }
}






@end
